<?php
/**
 * --------------------------------------------------------------
 * 支付宝支付集成封装类
 * Author: zd <kfzphp@126.com>
 * Date: 2018-06-01
 * Project: kfzphp.com
 * --------------------------------------------------------------
 */

if(APP_DEBUG) {
    ini_set("display_errors", "On");
    error_reporting(E_ALL);
}

class KfzAlipay
{
    /**
     * 初始化
     * @param  [type]     $data [description]
     */
    public function __construct($data)
    {
        // 基础数据
        $this->out_trade_no = $data['WIDout_trade_no'];
        $this->subject = $data['WIDsubject'];
        $this->total_amount = $data['WIDtotal_amount'];
        $this->body = $data['WIDbody'];
        // 接口路径
        $this->path = VENDOR_PATH . '/alipay/wap';
        // 支付宝配置
        $this->config = self::config();
    }

    /**
     * 返回支付宝配置参数
     * @return [type]     [description]
     */
    public function config()
    {
        $config = config('ALIPAY');
        return [
            'app_id' => $config['APPID'],
            'merchant_private_key' => $config['PRIVATE_KEY'],
            'notify_url' => $config['NOTIFY_URL'],
            'return_url' => $config['RETURN_URL'],
            'charset' => $config['CHARSET'],
            'sign_type' => $config['SIGN_TYPE'],
            'gatewayUrl' => $config['GATEWAY_URL'],
            'alipay_public_key' => $config['PUBLIC_KEY'],
        ];
    }

    /**
     * 支付
     * @return [type]     [description]
     */
    public function pay()
    {
        header("Content-type: text/html; charset=utf-8");

        require_once $this->path . '/wappay/service/AlipayTradeService.php';
        require_once $this->path . '/wappay/buildermodel/AlipayTradeWapPayContentBuilder.php';

        if (!empty($this->out_trade_no) && (trim($this->out_trade_no) != "") ){
            //商户订单号，商户网站订单系统中唯一订单号，必填
            $out_trade_no = $this->out_trade_no;

            //订单名称，必填
            $subject = $this->subject;

            //付款金额，必填
            $total_amount = $this->total_amount;

            //商品描述，可空
            $body = $this->body;

            //超时时间
            $timeout_express = "1m";

            $payRequestBuilder = new AlipayTradeWapPayContentBuilder();
            $payRequestBuilder->setBody($body);
            $payRequestBuilder->setSubject($subject);
            $payRequestBuilder->setOutTradeNo($out_trade_no);
            $payRequestBuilder->setTotalAmount($total_amount);
            $payRequestBuilder->setTimeExpress($timeout_express);

            $payResponse = new AlipayTradeService($this->config);
            $result = $payResponse->wapPay($payRequestBuilder, $this->config['return_url'], $this->config['notify_url']);

            return ;
        }
    }
}